package com.example.librarymanagersystem.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @GetMapping("/login")
    public ModelAndView login() {
        ModelAndView mav = new ModelAndView("login");
        return mav;
    }

    @PostMapping("/login")
    public String user(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            Model model,
            HttpServletRequest request) {
        if ("admin".equals(username) && "1".equals(password)) {
            request.getSession().setAttribute("username", username);
            return "redirect:/index";
        }
        model.addAttribute("msg", "用户名或密码错误");
        return "login";
    }

    @GetMapping("/index")
    public String home(HttpServletRequest request, Model model) {
        //登录拦截
        if (request.getSession().getAttribute("username") == null) {
            model.addAttribute("msg", "未登录");
            return "login";
        }
        return "book/index";
    }


    @GetMapping("/logout")
    public ModelAndView logout(
            HttpSession session,
            SessionStatus sessionStatus
    ) {
        ModelAndView mav = new ModelAndView();
        //退出逻辑
        //1.从会话对象中清除user属性
        session.removeAttribute("username");
        //2.使当前会话失效
        session.invalidate();
        //3.设置spring框架会话状态为已完成
        sessionStatus.setComplete();
        //4.将页面重定向到登录页面
        mav.setViewName("redirect:/login");
        return  mav;
    }


}
